<?php

namespace App\Http\Controllers\Index;

use App\Jobs\KillGoodsClear;
use App\Jobs\sendEmail;
use App\Models\AdminRole;
use App\Models\DuguVedio;
use App\Models\RolePermission;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;

class IndexController extends Controller
{
	public function index()
	{
//	    $roles = AdminRole::query()
//            ->select('role_id')
//            ->where('admin_id',2)->toSql();
//
//	    $permissions = RolePermission::query()->whereIn('role_id',function ($query){
//            $query->from('admin_role')->select('role_id')->where('admin_id',2)->get();
//        })->get()->pluck('permission_id')->toArray();
//
//	    echo '<pre>';
//	    var_dump($permissions);
//	    die;

//	    $user = Redis::hgetall('ws_admin_table');
//	    var_dump($user);

//	    phpinfo();
//	    die;
	    echo '首页';
//        /**@var \Swoole\WebSocket\Server $swoole */
//        $swoole = app('swoole');

//	    $fd = Redis::hget('ws_admin_table','uid_1');
//	    $swoole->push($fd,json_encode(['type'=>'msg','msg'=>111]));
//
	    /*$fd = 1;
	    $uid = 10;

	    Redis::hmset('ws:admin_group:role:1',[
	        'uid_'.$uid=>$fd,
            'fd_'.$fd=>$uid
        ]);

        $fd = 102;
        $uid = 13;

        Redis::hmset('ws:admin_group:role:1',[
            'uid_'.$uid=>$fd,
            'fd_'.$fd=>$uid
        ]);

        Redis::hdel('ws:admin_group:role:1','uid_' . 13);
        Redis::hdel('ws:admin_group:role:1','fd_' . 102);



        $fd = 103;
        $uid = 13;

        Redis::hmset('ws:admin_group:role:1',[
            'uid_'.$uid=>$fd,
            'fd_'.$fd=>$uid
        ]);
	    die;

	    $max_id = User::query()->max('id');

	    for($i=0;$i<200;$i++){
            $nextUserId = ++$max_id;
            $user_data = [
                'username'=>'user_id_' . $nextUserId,
                'nick_name'=>'用户_'.$nextUserId,
                'password'=>bcrypt(123456),
            ];

            $user = User::create($user_data);
            $user->user_info()->create([]);

            if($user->id){
                $useraddr = [
                    'username'=>$user_data['nick_name'],
                    'tel'=>'18779031200',
                    'province_id'=>'130000000000',
                    'city_id'=>'130400000000',
                    'county_id'=>'130421000000',
                    'default'=>'1',
                    'address'=>'东京都羽村车站--' . $user->id,
                ];

                $user->user_address()->create($useraddr);
            }
	    }


	    echo '<pre>';
	    var_dump($user);
//	    die;


//        Test::query()->where(['id'=>1])->update(['num'=>2]);
//        KillGoodsClear::dispatch(111);
//        dispatch(new sendEmail());

	    $a = Carbon::now()->addMinutes(1);
//
//	    echo '<pre>';
//	    var_dump($a);
//	    die;
		//Redis::set('xxx','fdsfds');

		//echo Redis::get('xxx');

		//99乘法表
		for($i=1;$i<=9;$i++){
		    for($j=1;$j<=$i;$j++){

		        echo $j . '*' . $i .'='. $i*$j . ' ';

		        if($j == $i){
		        	echo '<br>';
		        }
		    }
		}


		//面试题1 单foreach写法
		$data = [
			['group'=>'color','name'=>'red','id'=>1],
			['group'=>'color','name'=>'blue','id'=>2],
			['group'=>'size','name'=>'X','id'=>3],
			['group'=>'size','name'=>'XL','id'=>4],
			['group'=>'chima','name'=>'30','id'=>5],
		];

		$arr = [];
		$sort = [];
		$len = count($data) - 1;

		foreach ($data as $k => $v) {

			if(isset($arr['group']) && $v['group'] != $arr['group']){
			    $sort[] = $arr;
			    $arr = [];
			}

		    if(isset($arr['group']) && $arr['group'] == $v['group']){
		    	$arr['values'][] = $v['name'];
		    }else{
		    	$arr['group'] = $v['group'];
				$arr['values'][] = $v['name'];
			}

		    if($k == $len){
		        $sort[] = $arr;
		    }
		}


		/*foreach ($data as $k => $v) {

			if(isset($arr['group']) && $arr['group'] != $v['group']){
				$sort[] = $arr;
				$arr = [];
				$arr['group'] = $v['group'];
			    $arr['values'][] = $v['name'];
			}else if (isset($arr['group']) && $arr['group'] == $v['group']){
				$arr['values'][] = $v['name'];
			}else if (!isset($arr['group'])){
				$arr['group'] = $v['group'];
				$arr['values'][] = $v['name'];
			}else{
				$sort[] = $arr;
			}
		}

		$data = [
			['group'=>'color','name'=>'red','id'=>1],
			['group'=>'color','name'=>'blue','id'=>2],
			['group'=>'size','name'=>'X','id'=>3],
			['group'=>'size','name'=>'XL','id'=>4],
			['group'=>'chima','name'=>'30','id'=>5],
		];

		$spec = [
			[
				'group'=>'color',
				'values'=>
					[
						'id'=>1,
						'name'=>'blue',
					],
					[
						'id'=>2,
						'name'=>'red'

					]
			],
			[
				'group'=>'size',
				'values'=>
					[
						'id'=>3,
						'name'=>'X',
					]
			]
		];

		//面试题前端接口版 双foreach写法
		$groups = array_unique(array_column($data,'group'));

		$arr = [];

		$specs = [];
		foreach ($groups as $k => $v) {
		    foreach ($data as $k1 => $v1) {
		        if($v1['group'] == $v){
		        	$arr['group'] = $v;
		        	$arr['values'][] = [
		        		'id'=>$v1['id'],
						'name'=>$v1['name'],
					];
		        }
		    }

		    $specs[] = $arr;
		    $arr = [];
		}*/
	}

	public function indexss(Request $request)
	{

		phpinfo();


		$path = $request->url();

		// 不附带查询串...
		$url = $request->url();

		var_dump($url);
		// 附带查询串...
		$url = $request->fullUrl();

		var_dump($url);


		//获取请求 Method
		$method = $request->method();
		echo "请求方法是：" . $method . "<br>";

		if ($request->isMethod('get')) {
			var_dump($method);
			echo "get";
		}

		echo '<pre>';
//		var_dump($path);
//		die;
	}

	public function setCookie()
	{
		$cookie = cookie('ceshi2','123456',3600);
		response('ss')->cookie($cookie);
	}

	public function getCookie()
	{
		echo request()->cookie('test');
	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function create(Request $request)
	{
		$users = \DB::table('users')->pluck('id','name')->toArray();
		echo '<pre>';
		var_dump($users);
//		die;


//		echo url()->current();
//		echo '<br>';

// Get the current URL including the query string...
//		echo url()->full();
//		echo '<br>';
// Get the full URL for the previous request...
//		echo url()->previous();

//		$this->setCookie();
		//设置cookie
//		$av =  response('ssss')->cookie('abc2','value',3600);
//
//		$cookie = $request->cookie('abc');
//		var_dump($cookie);
//
//
//        $param = $request->input('test');
//        var_dump($param);
//        $queryParam = $request->query('test');
//        var_dump($queryParam);
	}



	public function dikaer()
	{
		echo '笛卡尔积';

		$arr = [
			'7'=>[
				'白色',
				'黑色',
				'绿色',
			],
			'10'=>[
				'M',
				'L',
				'XL',
				'XXXL'
			],
			'12'=>[
				'纯棉',
				'聚氯乙烯',
				'丝绸',
			],
			'15'=>[
				'青年',
				'学生'
			]
		];

		$attr = [
			'7'=>[
				'2'=>'蓝色',
				'5'=>'白色'
			],
			'8'=>[
				'3'=>'X',
				'1'=>'L',
				'4'=>'XL'
			],
			'10'=>[
				'9'=>'纯棉',
				'11'=>'透气'
			],
			'14'=>[
				'22'=>'英伦',
				'23'=>'日韩',
				'24'=>'复古'
			]
		];

		$this->mydikaer($attr);
	}


	public function mydikaer($data)
	{
		//抛出要计算的数组的第一个数组
		$arr = array_shift($data);

		$i = 0;
		foreach ($data as $k => $item) {
			$res = [];
			if($i == 0){
				foreach ($arr as $k1 => $v1) {
					foreach ($item as $k2 => $v2) {
						$tmp = [];
						$tmp[$k1] = $v1;
						$tmp[$k2] = $v2;
						$res[] = $tmp;
					}
				}
				$arr = $res;
			}else{
				foreach ($arr as $k1 => $v1) {
					foreach ($item as $k2 => $v2) {
						$v1[$k2] = $v2;
						$res[] = $v1;
						array_pop($v1);
					}

				}
				$arr = $res;
			}
			$i++;
		}

		return $arr;
	}




	public function dikaerji($data)
	{
		$result = array();
		foreach (array_shift($data) as $k=>$item) {
			$result[] = array($k=>$item);
		}

		foreach ($data as $k => $v) {
			$result2 = [];
			foreach ($result as $k1=>$item1) {
				foreach ($v as $k2=>$item2) {
					$temp     = $item1;
					$temp[$k2]   = $item2;
					$result2[] = $temp;
				}
			}
			echo '<pre>';
			var_dump($result2);
			$result = $result2;
		}

		echo '<pre>';
		var_dump($result);
//		die;
	}

	/**
	 ** 实现二维数组的笛卡尔积组合
	 ** $arr 要进行笛卡尔积的二维数组
	 ** $str 最终实现的笛卡尔积组合,可不写
	 ** @return array
	 **/
	function cartesian($arr,$str = array()){
		//去除第一个元素
		$first = array_shift($arr);
		//判断是否是第一次进行拼接
		if(count($str) > 1) {
			foreach ($str as $k => $val) {
				foreach ($first as $key => $value) {
					//最终实现的格式 1,3,76
					//可根据具体需求进行变更
					$str2[] = $val.','.$value;
				}
			}
		}else{
			foreach ($first as $key => $value) {
				//最终实现的格式 1,3,76
				//可根据具体需求进行变更
				$str2[] = $value;
			}
		}

		//递归进行拼接
		if(count($arr) > 0){
			$str2 = $this->cartesian($arr,$str2);
		}
		//返回最终笛卡尔积
		echo '<pre>';
		var_dump($str2);
//		die;
	}


    /**
     * 获取百度下拉菜单
     * User: ihome
     */
    public function getBaiduDownMenu(Request $request)
	{
        $keyWord = $request->input('keyword');

        if(mb_strlen($keyWord) < 1){
            return response()->json([
                'code'=>404,
            ]);
        }

        $url = 'https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=30748,1445,21086,30788,26350,22160&wd='.urlencode($keyWord).'&req=2&csor=2&pwd=dongj';
        $res = http_curl($url);

        $list = [];

        if(isset($res['g'])){

            foreach ($res['g'] as $k => $v) {
                $list[] = $v['q'];
            }

            return response()->json([
                'code'=>200,
                'msg'=>'ok',
                'data'=>$list
            ]);
        }else{
            return response()->json([
                'code'=>404,
            ]);
        }
	}


	public function duguVedioUpdate(){
		$url = 'https://www.ixigua.com/home/4076588298929316/video/?preActiveKey=hotsoon';

//        $query = QueryList::get($url);
//
//		$title = $query->find('title')->texts();

		$text = file_get_contents($url);

		$text = strstr($text,'window._SSR_HYDRATED_DATA=');

		$text = str_replace(['window._SSR_HYDRATED_DATA=','</script></body></html>'],'',$text);

		$fetchData = json_decode($text,true);
		$fetchData = $fetchData['AuthorHomeVideoList']['videos']['0'];

		$check = DuguVedio::query()->where(['groupId'=>$fetchData['groupId']])->first();

		if(!$check){
			$data = [
				'groupId'=>$fetchData['groupId'],
				'title'=>$fetchData['title'],
				'abstract'=>$fetchData['abstract'],
				'duration'=>gmstrftime('%M:%S',$fetchData['duration']),
				'playNum'=>$fetchData['playNum'],
				'publishTime'=>date('Y-m-d H:i:s',$fetchData['publishTime']),
			];

			DuguVedio::create($data);

			$email_text = $data['publishTime'] .':'.$data['abstract'];

			\Mail::raw($email_text,function ($message) use ($data){
				$message->to('hxxk@qq.com')->subject($data['duration'] . ' ' . $data['title']);
			});
		}
	}
}
